package com.smartum.mpr.client.view;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.smartgwt.client.data.RecordList;
import com.smartgwt.client.widgets.Canvas;
import com.smartgwt.client.widgets.IButton;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridField;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.grid.events.CellClickEvent;
import com.smartgwt.client.widgets.grid.events.CellClickHandler;
import com.smartgwt.client.widgets.grid.events.EditCompleteEvent;
import com.smartgwt.client.widgets.grid.events.EditCompleteHandler;
import com.smartgwt.client.widgets.layout.HLayout;
import com.smartgwt.client.widgets.layout.VLayout;
import com.smartum.mpr.client.presenter.JobsViewerPresenter;
import com.smartum.mpr.client.services.JobsService;
import com.smartum.mpr.client.services.JobsServiceAsync;
import com.smartum.mpr.shared.Category;
import com.smartum.mpr.shared.Subcategory;

import java.util.List;

/**
 */
public class JobsViewer extends VLayout implements JobsViewerPresenter.Display {
    final ListGrid newsCategoriesListGrid;
    final ListGrid newsSubcategoriesListGrid;
    List<Category> storedCategories;

    public JobsViewer() {
        GWT.log("[CONSTRUCT COMPONENT] jobs");
        HLayout jobsUpdateLayout = new HLayout(10);
        jobsUpdateLayout.setHeight100();
        jobsUpdateLayout.setWidth100();

        VLayout jobsGrid = new VLayout();
        newsCategoriesListGrid = new ListGrid();
        newsCategoriesListGrid.setHeight100();
        newsCategoriesListGrid.setShowAllRecords(true);
        newsCategoriesListGrid.setShowEmptyMessage(true);
        newsCategoriesListGrid.setEmptyMessage("There's no jobs to display");

        ListGridField nameField = new ListGridField("name", "Jobs");
        newsCategoriesListGrid.setFields(nameField);
        newsCategoriesListGrid.setShowHeader(false);
        newsCategoriesListGrid.setCanEdit(true);
        newsCategoriesListGrid.addCellClickHandler(new CellClickHandler() {
            public void onCellClick(CellClickEvent event) {
                final ListGridRecord selectedRecord = newsCategoriesListGrid.getSelectedRecord();
                final String id = selectedRecord.getAttribute("id");

                for (Category category : storedCategories) {

                    if (id.equals(category.getCategoryId().toString())) {
                        updateSubgrid(category.getSubcategories());
                    }
                }
            }
        });
        newsCategoriesListGrid.addEditCompleteHandler(new EditCompleteHandler() {
            public void onEditComplete(final EditCompleteEvent event) {

                final ListGridRecord record = newsCategoriesListGrid.getRecord(event.getRowNum());
                final String id = record.getAttribute("id");
                if (id != null && !id.isEmpty()) {
                    final String name = record.getAttribute("name");
                    final JobsServiceAsync jobsServiceAsync = GWT.create(JobsService.class);
                    jobsServiceAsync.editCategory(id, name, new AsyncCallback<List<Category>>() {
                        public void onFailure(Throwable caught) {
                        }

                        public void onSuccess(List<Category> result) {
                            storedCategories = result;
                            updateGrids(result);
                            newsCategoriesListGrid.selectRecord(event.getRowNum());
                            final List<Subcategory> subcategories = result.get(event.getRowNum()).getSubcategories();
                            updateSubgrid(subcategories);
                            if (subcategories.size() != 0) {
                                newsSubcategoriesListGrid.selectRecord(0);
                            }
                        }
                    });
                } else {
                    addNewCategory(event, record);
                }
            }
        });

        jobsGrid.addMember(newsCategoriesListGrid);

        VLayout jobControls = new VLayout(5);
        jobControls.setWidth(120);

        IButton addNewJobCategory = new IButton("Add job");
        addNewJobCategory.setWidth(120);
        addNewJobCategory.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                newsCategoriesListGrid.startEditingNew();
            }
        });
        IButton deleteJobCategory = new IButton("Delete job");
        deleteJobCategory.setWidth(120);
        deleteJobCategory.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                final JobsServiceAsync jobsServiceAsync = GWT.create(JobsService.class);
                final ListGridRecord selectedRecord = newsCategoriesListGrid.getSelectedRecord();
                jobsServiceAsync.deleteCategory(selectedRecord.getAttribute("id"), new AsyncCallback<List<Category>>() {
                    public void onFailure(Throwable caught) {
                        //To change body of implemented methods use File | Settings | File Templates.
                    }

                    public void onSuccess(List<Category> result) {
                        storedCategories = result;
                        updateGrids(result);

                        if (result.size() != 0) {
                            updateSubgrid(result.get(0).getSubcategories());
                        }
                        newsCategoriesListGrid.selectRecord(0);
                    }
                });
            }
        });
        jobControls.addMember(addNewJobCategory);
        //jobControls.addMember(deleteJobCategory);

        VLayout jobSubcategoryGrid = new VLayout();

        VLayout jobSubcategoryControls = new VLayout(5);
        jobSubcategoryControls.setWidth(120);
        IButton addNewJobSubcategory = new IButton("Add Subcategory");
        addNewJobSubcategory.setWidth(120);
        addNewJobSubcategory.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                newsSubcategoriesListGrid.startEditingNew();
            }
        });
        IButton deleteSubCategory = new IButton("Delete Subcategory");
        deleteSubCategory.setWidth(120);
        deleteSubCategory.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                final JobsServiceAsync jobsServiceAsync = GWT.create(JobsService.class);
                final ListGridRecord selectedRecord = newsSubcategoriesListGrid.getSelectedRecord();
                final int selectedRecordIndex = newsCategoriesListGrid.getRecordIndex(newsCategoriesListGrid.getSelectedRecord());
                if (selectedRecord == null) {
                    return;
                }
                jobsServiceAsync.deleteSubCategory(selectedRecord.getAttribute("id"), new AsyncCallback<List<Category>>() {
                    public void onFailure(Throwable caught) {
                    }

                    public void onSuccess(List<Category> result) {
                        storedCategories = result;

                        if (result.size() != 0 && result.get(selectedRecordIndex).getSubcategories().size() != 0) {
                            updateSubgrid(result.get(selectedRecordIndex).getSubcategories());
                            newsSubcategoriesListGrid.selectRecord(0);
                        }
                    }
                });
            }
        });
        jobSubcategoryControls.addMember(addNewJobSubcategory);
        //jobSubcategoryControls.addMember(deleteSubCategory);

        newsSubcategoriesListGrid = new ListGrid();
        newsSubcategoriesListGrid.setHeight100();
        newsSubcategoriesListGrid.setShowAllRecords(true);
        newsSubcategoriesListGrid.setShowEmptyMessage(true);
        newsSubcategoriesListGrid.setShowHeader(false);
        newsSubcategoriesListGrid.setCanEdit(true);
        newsSubcategoriesListGrid.setEmptyMessage("There's no job subcategories to display");

        newsSubcategoriesListGrid.addEditCompleteHandler(new EditCompleteHandler() {
            public void onEditComplete(final EditCompleteEvent event) {

                final ListGridRecord record = newsSubcategoriesListGrid.getRecord(event.getRowNum());
                final String id = record.getAttribute("id");
                final ListGridRecord categoryRecord = newsCategoriesListGrid.getSelectedRecord();
                final int selectedRecordIndex = newsCategoriesListGrid.getRecordIndex(categoryRecord);
                if (id != null && !id.isEmpty()) {
                    final String name = record.getAttribute("name");

                    final JobsServiceAsync jobsServiceAsync = GWT.create(JobsService.class);
                    jobsServiceAsync.editSubCategory(id, name, new AsyncCallback<List<Category>>() {
                        public void onFailure(Throwable caught) {
                        }

                        public void onSuccess(List<Category> result) {
                            storedCategories = result;
                            if (result.size() != 0 && result.get(selectedRecordIndex).getSubcategories().size() != 0) {
                                updateSubgrid(result.get(selectedRecordIndex).getSubcategories());
                                newsSubcategoriesListGrid.selectRecord(0);
                            }
                        }
                    });
                } else {
                    addNewSubcategory(event, record, categoryRecord.getAttribute("id"), selectedRecordIndex);
                }
            }
        });

        ListGridField subcatigoryNameField = new ListGridField("name", "Subcategories");
        newsSubcategoriesListGrid.setFields(subcatigoryNameField);
        jobSubcategoryGrid.addMember(newsSubcategoriesListGrid);

        final JobsServiceAsync jobsServiceAsync = GWT.create(JobsService.class);
        jobsServiceAsync.getCategories(new AsyncCallback<List<Category>>() {
            public void onFailure(Throwable caught) {
            }

            public void onSuccess(List<Category> result) {
                storedCategories = result;
                updateGrids(result);

                if (result.size() != 0) {
                    updateSubgrid(result.get(0).getSubcategories());
                }
                newsCategoriesListGrid.selectRecord(0);
            }
        });

        jobsUpdateLayout.addMember(jobsGrid);
        jobsUpdateLayout.addMember(jobControls);
        jobsUpdateLayout.addMember(jobSubcategoryGrid);
        jobsUpdateLayout.addMember(jobSubcategoryControls);

        addMember(jobsUpdateLayout);
    }

    private void addNewCategory(final EditCompleteEvent event, ListGridRecord record) {
        final String name = record.getAttribute("name");
        if (name != null && !name.isEmpty()) {
            final JobsServiceAsync jobsServiceAsync = GWT.create(JobsService.class);
            jobsServiceAsync.addCategory(name, new AsyncCallback<List<Category>>() {
                public void onFailure(Throwable caught) {
                }

                public void onSuccess(List<Category> result) {
                    storedCategories = result;
                    updateGrids(result);
                    newsCategoriesListGrid.selectRecord(event.getRowNum());
                    updateSubgrid(result.get(result.size() - 1).getSubcategories());
                }
            });
        } else {
            newsCategoriesListGrid.removeData(record);
        }
    }

    private void addNewSubcategory(final EditCompleteEvent event, ListGridRecord record, String id, final int selectedRecordIndex) {
        final String name = record.getAttribute("name");
        if (name != null && !name.isEmpty()) {
            final JobsServiceAsync jobsServiceAsync = GWT.create(JobsService.class);
            jobsServiceAsync.addSubCategory(id, name, new AsyncCallback<List<Category>>() {
                public void onFailure(Throwable caught) {
                }

                public void onSuccess(List<Category> result) {
                    storedCategories = result;
                    if (result.size() != 0 && result.get(selectedRecordIndex).getSubcategories().size() != 0) {
                        updateSubgrid(result.get(selectedRecordIndex).getSubcategories());
                        newsSubcategoriesListGrid.selectRecord(0);
                    }
                }
            });
        } else {
            newsCategoriesListGrid.removeData(record);
        }
    }

    private void updateGrids(List<Category> result) {
        final RecordList recordList = new RecordList();
        for (Category category : result) {
            final ListGridRecord record = new ListGridRecord();
            record.setAttribute("id", category.getCategoryId());
            record.setAttribute("name", category.getCategoryName());

            recordList.add(record);
        }
        newsCategoriesListGrid.setData(recordList);
    }

    private void updateSubgrid(List<Subcategory> result) {
        final RecordList recordList = new RecordList();
        for (Subcategory subcategory : result) {
            final ListGridRecord record = new ListGridRecord();
            record.setAttribute("id", subcategory.getSubCategoryId());
            record.setAttribute("name", subcategory.getSubCategoryName());

            recordList.add(record);
        }
        newsSubcategoriesListGrid.setData(recordList);
    }

    @Override
    public Canvas getJobsViewerWidget() {
        return this;
    }
}
